package cn.swenty.backstage.sso.server.web;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import zy.mp.backstage.framework.service.ServiceFactory;

/** 
* @ClassName: LoginController 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author sunyang
* @date 2018年1月26日 上午10:21:54 
*  
*/
@Controller
public class LoginController {
	
	
	
	@RequestMapping("/")
    public String index(Model model) {
        return "index";
    }


    @RequestMapping("/login")
    public String showLoginForm(HttpServletRequest req, Model model) {
    	
    	if(SecurityUtils.getSubject().getPrincipal()!=null){
    		return "index";
    	}
        String exceptionClassName = (String)req.getAttribute("shiroLoginFailure");
        String error = null;
        if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
            error = "用户不存在";
        } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
        }else if(DisabledAccountException.class.getName().equals(exceptionClassName)){
        	error = "账号被禁用";
        }else if(ExcessiveAttemptsException.class.getName().equals(exceptionClassName)){
        	error = "账号被锁定";
        }else if(exceptionClassName != null) {
            error = "其他错误";
        }
        req.setAttribute("error", error);
        return "login";
    }
    
    @RequestMapping("/logout")
    public String exit(HttpServletRequest req, Model model) {
    	SecurityUtils.getSubject().logout();
    	return "login";
    }
    
    @RequestMapping(value = "/removeLimit")
    public String removeLimit(HttpServletRequest req, Model model) {
    	CacheManager cacheManager = (CacheManager) ServiceFactory.getBean("cacheManager");
    	Cache<String, Object> c = cacheManager.getCache("passwordRetryCache");
    	c.remove(req.getParameter("account"));
    	return "index";
    }


}
